//
//  DebugSandBoxViewController.m
//  YK_DebugManager
//
//  Created by edward on 2021/6/1.
//

#import "DebugSandBoxViewController.h"
#import "DebugSandBoxFileDetailViewController.h"
#import "UIImage+DebugManager.h"

#pragma mark -------model-------

@interface DebugSandBoxModel : NSObject
///
@property(nonatomic,copy) NSString *path;
///
@property(nonatomic,copy) NSString *fullPath;
///
@property(nonatomic,copy) NSString *imageName;
///
@property(nonatomic,assign) BOOL isDir;
///
@property(nonatomic,assign) NSInteger fileSize;
///
@property(nonatomic,copy) NSString *size;
@end

@implementation DebugSandBoxModel



@end

#pragma mark -------cell-------

@interface DebugSandBoxCell : UITableViewCell

- (void)loadModel:(DebugSandBoxModel *)model;
///
@property(nonatomic,strong) UIImageView *typeImageView;
///
@property(nonatomic,strong) UILabel *titleLabel;
///
@property(nonatomic,strong) UILabel *sizeLabel;
@end

@implementation DebugSandBoxCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        if (@available(iOS 13.0, *)) {
            self.backgroundColor = UIColor.systemBackgroundColor;
        } else {
            self.backgroundColor = UIColor.whiteColor;
        }
        self.contentView.backgroundColor = UIColor.clearColor;
        [self setupUI];
    }
    return self;
}

- (void)loadModel:(DebugSandBoxModel *)model
{
    self.typeImageView.image = [UIImage debugmanager_imageNamed:model.imageName];
    self.titleLabel.text = model.path;
    self.sizeLabel.text = model.size;
}

- (void)setupUI
{
    self.backgroundColor = UIColor.clearColor;
    self.contentView.backgroundColor = UIColor.clearColor;
    self.typeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(debug_lengthWithScale(16), debug_lengthWithScale(12), debug_lengthWithScale(24), debug_lengthWithScale(24))];
    self.typeImageView.backgroundColor = UIColor.whiteColor;
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.typeImageView.frame) + debug_lengthWithScale(16), debug_lengthWithScale(14.5), debug_lengthWithScale(225), debug_lengthWithScale(19.5))];
    self.titleLabel.font = [UIFont systemFontOfSize:16];
    if (@available(iOS 13.0, *)) {
        self.titleLabel.textColor = UIColor.labelColor;
    } else {
        self.titleLabel.textColor = UIColor.blackColor;
    }
    self.sizeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.titleLabel.frame) + debug_lengthWithScale(17), debug_lengthWithScale(14.25), debug_lengthWithScale(62.5), debug_lengthWithScale(19.5))];
    self.sizeLabel.textColor = UIColor.lightGrayColor;
    self.sizeLabel.font = [UIFont systemFontOfSize:16];
    self.sizeLabel.textAlignment = NSTextAlignmentRight;
    [self.contentView addSubview:self.typeImageView];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.sizeLabel];
}


@end

#pragma mark -------main-------
@interface DebugSandBoxViewController ()<UITableViewDelegate,UITableViewDataSource>
///
@property(nonatomic,strong) UITableView *tableView;
///
@property(nonatomic,strong) NSMutableArray<DebugSandBoxModel *> *list;
///
@property(nonatomic,copy) NSString *fileUrl;

@end

@implementation DebugSandBoxViewController

- (instancetype)initWithFileUrl:(NSString * _Nullable )fileUrl title:(NSString *)title
{
    self = [super init];
    if (self) {
        self.fileUrl = fileUrl?:NSHomeDirectory();
        self.title = title;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.tableView];
    [self initPath];
}

- (void)initPath
{
    NSMutableArray *files = @[].mutableCopy;
    NSError *error = nil;
    NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.fileUrl error:&error];
    if (!error) {
        for (NSString *path in paths) {
            BOOL isDir = false;
            NSString *fullPath = [self.fileUrl stringByAppendingPathComponent:path];
            [[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir];
            
            DebugSandBoxModel *model = [[DebugSandBoxModel alloc] init];
            model.path = path;
            model.fullPath = fullPath;
            model.isDir = isDir;
            model.imageName = isDir?@"ic_main_item_sandbox_dictionary":@"ic_main_item_sandbox_file";
            NSInteger fileSize = [self fileSizeWithPath:fullPath];
            NSString *fileSizeStr = nil;
            if (fileSize > 1024 * 1024){
                fileSizeStr = [NSString stringWithFormat:@"%.2fM",fileSize / 1024.00f /1024.00f];
                
            }else if (fileSize > 1024){
                fileSizeStr = [NSString stringWithFormat:@"%.2fKB",fileSize / 1024.00f ];
                
            }else{
                fileSizeStr = [NSString stringWithFormat:@"%.2fB",fileSize / 1.00f];
            }
            model.fileSize = fileSize;
            model.size = fileSizeStr;
            [files addObject:model];
        }
    }
    self.list = files;
    [self.tableView reloadData];
}

- (NSInteger)fileSizeWithPath:(NSString *)path{
    NSInteger fileSize = 0;
    NSFileManager * fileManger = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL isExist = [fileManger fileExistsAtPath:path isDirectory:&isDir];
    if (isExist){
        if(isDir){
            //文件夹
            NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:path error:nil];
            NSString * subPath = nil;
            for(NSString *str in dirArray) {
                subPath = [path stringByAppendingPathComponent:str];
                fileSize += [self fileSizeWithPath:subPath];
            }
        }else{
            //文件
            NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
            NSInteger size = [dict[@"NSFileSize"] integerValue];
            fileSize += size;
        }
    }else{
        NSLog(@"不存在该文件");
    }
    return fileSize;
}

#pragma mark -tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugSandBoxCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(DebugSandBoxCell.class) forIndexPath:indexPath];
    [cell loadModel:self.list[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugSandBoxModel *model = self.list[indexPath.row];
    if (model.isDir) {
        DebugSandBoxViewController *vc = [[DebugSandBoxViewController alloc] initWithFileUrl:model.fullPath title:model.path];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self action:model.fullPath];
    }
}

- (UITableView *)tableView
{
    if(!_tableView)
    {
        UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 85;
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.backgroundColor = UIColor.whiteColor;
        [tableView registerClass:DebugSandBoxCell.class forCellReuseIdentifier:NSStringFromClass(DebugSandBoxCell.class)];
        _tableView = tableView;
    }
    return _tableView;
}

- (void)action:(NSString *)path
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"你要执行的操作" message:@"查看或分享" preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof(self) weakself = self;
    UIAlertAction *prewAction = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself previewWithPath:path];
    }];
    UIAlertAction *shareAction = [UIAlertAction actionWithTitle:@"分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself shareWithPath:path];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:prewAction];
    [alertVC addAction:shareAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)previewWithPath:(NSString *)path
{
//    预览
    DebugSandBoxFileDetailViewController *vc = [[DebugSandBoxFileDetailViewController alloc] initWithFilePath:path];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)shareWithPath:(NSString *)path
{
    id object = [NSURL fileURLWithPath:path];
    if (!object) {
        return;
    }
    NSArray *objectsToShare = @[object];//support NSString、NSURL、UIImage

    UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];

    if([[UIDevice currentDevice].model isEqualToString:@"iPad"]){
        if ( [controller respondsToSelector:@selector(popoverPresentationController)] ) {
            controller.popoverPresentationController.sourceView = self.view;
        }
        [self presentViewController:controller animated:YES completion:nil];
    }else{
        [self presentViewController:controller animated:YES completion:nil];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
